package com.zengqingfa.rocketmq.batch;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;

/**
 *
 * @fileName: BatchMessageConsumer
 * @author: zengqf3
 * @date: 2021-4-2 16:21
 * @description:
 */
public class BatchMessageConsumer {

    public static void main(String[] args) throws Exception {

        // 1、创建DefaultMQPushConsumer
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("demo_consumer_broadcasting_group");

        // 2、设置namesrv地址
        consumer.setNamesrvAddr("localhost:9876");

        // 3、默认是集群模式，
        // consumer.setMessageModel(MessageModel.BROADCASTING);

        // 4、、设置消息拉取最大数
        consumer.setConsumeMessageBatchMaxSize(2);

        // 5、、设置subscribe，这里是要读取订单主题信息
        // topic：指定消费的主题，subExpression：过滤规则
        consumer.subscribe("TestTopic", "BATCH");

        // 6、创建消息监听MessageListener
        consumer.setMessageListener((MessageListenerConcurrently) (list, consumeConcurrentlyContext) -> {
            // 迭代消息
            for (MessageExt msg : list) {
                // 获取主题
                String topic = msg.getTopic();
                // 获取标签
                String tags = msg.getTags();
                // 获取信息
                try {
                    // 7、获取消息信息
                    String result = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET);
                    System.out.println("Consumer_A消费信息----topic: " + topic + ", tags: " + tags + ", result: " + result);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    // 消息重试
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
            // 8、返回消息读取状态
            // 消息消费成功
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });

        // 开启Consumer
        consumer.start();
    }
}
